#! /usr/local/bin/python
"""
Author: Andy Nagels
Date: 2010-03-09
Clibet: Insert betting data in clipf.

Copyright (C) 2010 Andy Nagels

This file is part of Clibet.

Clibet is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Clibet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Clibet. If not, see <http://www.gnu.org/licenses/>.
					
"""

import sys, getopt, ConfigParser, time, datetime, os#, psycopg2 as dbapi2
from subprocess import call
from string import strip


class Clibet:
 
    def get_pprog(self):
        """ pprog """
        return self._pprog
    
    def set_pprog(self, name):
        """ set pprog """
        self._pprog = name
    
    pprog = property(get_pprog, set_pprog)
    
    def get_pversion(self):
        """ pversion """
        return self._pversion
    
    def set_pversion(self, version):
        """ set pversion """
        self._pversion = version
    
    pversion = property(get_pversion, set_pversion)
     
    def get_prelease(self):
        """ prelease """
        return self._prelease
    
    def set_prelease(self, release):
        """ set prelease """
        self._prelease = release
    
    prelease = property(get_prelease, set_prelease)
     
    def get_pdate(self):
        """ pdate """
        return self._pdate
    
    def set_pdate(self, date):
        """ set pdate """
        self._pdate = date
    
    pdate = property(get_pdate, set_pdate)
     
    def get_exitstate(self):
        """ Run or exit program? """
        return self._exitstate

    def set_exitstate(self, state):
        """ Set run-/exitstate """
        self._exitstate = state

    exitstate = property(get_exitstate, set_exitstate)
    
    def get_myconf(self):
        """ myconf """
        return self._myconf
    
    def set_myconf(self, version):
        """ set myconf """
        self._myconf = version
    
    myconf = property(get_myconf, set_myconf)

    def get_myacc(self):
        """ myacc """
        return self._myacc
    
    def set_myacc(self, version):
        """ set myacc """
        self._myacc = version
    
    myacc = property(get_myacc, set_myacc)

    def get_dbname(self):
        """ dbname """
        return self._dbname
    
    def set_dbname(self, version):
        """ set dbname """
        self._dbname = version
    
    dbname = property(get_dbname, set_dbname)

    def get_dbuser(self):
        """ dbuser """
        return self._dbuser
    
    def set_dbuser(self, version):
        """ set dbuser """
        self._dbuser = version
    
    dbuser = property(get_dbuser, set_dbuser)

    def get_dbpass(self):
        """ dbpass """
        return self._dbpass
    
    def set_dbpass(self, version):
        """ set dbpass """
        self._dbpass = version
    
    dbpass = property(get_dbpass, set_dbpass)

    def get_tblfinance(self):
        """ tblfinance """
        return self._tblfinance
    
    def set_tblfinance(self, version):
        """ set tblfinance """
        self._tblfinance = version
    
    tblfinance = property(get_tblfinance, set_tblfinance)

    def get_tblbets(self):
        """ tblbets """
        return self._tblbets
    
    def set_tblbets(self, version):
        """ set tblbets """
        self._tblbets = version
    
    tblbets = property(get_tblbets, set_tblbets)

    def get_tblcurbets(self):
        """ tblcurbets """
        return self._tblcurbets
    
    def set_tblcurbets(self, version):
        """ set tblcurbets """
        self._tblcurbets = version
    
    tblcurbets = property(get_tblcurbets, set_tblcurbets)

    def __init__(self):
        """ Init of main class """
        self.set_pprog('clibet.py')
        self.set_pversion('0.01a')
        self.set_prelease('Caveman')
        self.set_pdate('2010-03-09')
        self.set_exitstate(0)
        self.set_myconf(self.fConfFile())
        self.fConfig()
   
    def fConfFile(self):
        """ Get config file path from XDG_CONFIG_DIR. """
        # TODO: get from env var
        #self.set_myconf('~/.config/clibet/clibet.rc')
        return 'config/clibet/clibet.rc'

    def fDataDir(self):
        """ Get data file path from XDG_DATA_DIR. """
        # TODO: get from env var
        #self.set_mydata('~/.local/clibet/')
        return 'config/clibet/list'

    def fConfig(self):
        """ Retrieve config file values """
        config = ConfigParser.RawConfigParser()
        config.read(self.get_myconf())

        dbname = config.get('database', 'name')
        self.set_dbname(dbname)        
        dbuser = config.get('database', 'user')
        self.set_dbuser(dbuser)        
        dbpass = config.get('database', 'password')
        self.set_dbpass(dbpass)        
        tblfinance = config.get('data', 'tablefinance')
        self.set_tblfinance(tblfinance)        
        tblbets = config.get('data', 'tablebets')
        self.set_tblbets(tblbets)        
        tblcurbets = config.get('data', 'tablecurbets')
        self.set_tblcurbets(tblcurbets)        

    def fUsage(self):
	    """ Print usage info and exit """
	    print self.get_pprog() + ''' : Cli betting front-end for clipf.
	Options: 
	    -h : displays this help message
	    --version : displays version
	    --python : displays Python version'''

    def fRun(self):
        """ This is the main driver for the program. """
        # Test code.
        now = datetime.datetime.now()
        #print now.strftime("%Y-%m-%d %H:%M:%S") + ": running main thread ..."
        # Main method to call, goes here
        date = raw_input('When was the bet placed? ').strip().lower()
        teamA = raw_input('Team A: ').strip().lower()
        teamB = raw_input('Team B: ').strip().lower()
        matchdate = raw_input('Date of match: ').strip().lower()
        matchtime = raw_input('Time of match: ').strip().lower()
        choice = raw_input('Which team will you bet on? [A|B] ').strip().lower()
        pool = raw_input('How much is your bet: ').strip().lower()
        print ''
        print teamA + ' vs ' + teamB
        print '-'*len(teamA) + '----' + '-'*len(teamB)
        print 'Date: ' + date + '.'
        print 'Match will be on ' + matchdate + ' at ' + matchtime + '.'
        print 'Your bet is ' + pool + ' on',
        if choice == 'a':
            print teamA
        elif choice == 'b':
            print teamB
        else:
            print 'Error: unknown team choice.'
        # string needs to be in the form of
        # op add -d 2010-03-15 bet.place 3.00 "Calgary Flames vs. Detroit Redwings,B,2010-03-16 0200"
        # or
        # op add -d 2010-03-16 bet.cashin 4.15 "Calgary Flames vs. Detroit Redwings,3-4"

        sys.exit(0)

        #db = dbapi2.connect (database=self.get_dbname(), user=self.get_dbuser(), password=self.get_dbpass())
        #cur = db.cursor()
	    #TODO: use <dbname> ?
        cur.execute ("""select id, date, acc, amount, prod, flag, comment from finance""")
        
        cur.close()
        db.close()

    def fSanity(self):
        """ Sanity check for setup: Does a table already exist? """
        print "Check for existence tables?"

def fMain():
    """ Main driver, startup and cli options parsing. """
    # Gonna switch this to optparse later
    try:
        options, xarguments = getopt.getopt(sys.argv[1:], 'hr:a:', ['version', 'python'])
    except getopt.error,err:
        print 'Error: ' + str(err)
        sys.exit(1)

    cl = Clibet()

    for opt in options[:]:
        if opt[0] == '-h':
            cl.fUsage()
            cl.set_exitstate(1) # don't run the program after the optionparsing
            break
    for opt in options[:]:
        if opt[0] == '-a':
            print 'test: ' + str(opt[1]) # perhaps support multiple accounts later?
    	    cl.set_myacc(opt[1].strip())
            break
    for opt in options[:]:
        if opt[0] == '--version':
            print cl.get_pprog() + ' version '+ cl.get_pversion() + ' (' + cl.get_pdate() + '), \'' + cl.get_prelease() + '\' release.'
            cl.set_exitstate(1)
            break
    for opt in options[:]:
        if opt[0] == '--python':
            print 'Python '+sys.version
            cl.set_exitstate(1)
            break

    if(cl.get_exitstate() == 1):
        sys.exit(0)
    else:
        cl.fRun() #run the main method for the program

if __name__ == "__main__":
    fMain()
